package com.bmadmin.controller.zcgl;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bmadmin.domain.Datagrid;
import com.bmadmin.domain.LayUiDataTablePOJO;
import com.bmadmin.domain.MainDbDomain;
import com.bmadmin.domain.NormalResult;
import com.bmadmin.domain.SysUsersPOJO;
import com.bmadmin.domain.ZcckDomain;
import com.bmadmin.domain.ZcckmxcxDomain;
import com.bmadmin.domain.ZccktjcxDomain;
import com.bmadmin.domain.ZcwhDomain;
import com.bmadmin.service.ZcckService;
import com.bmadmin.service.ZcrkService;
import com.bmadmin.service.ZcwhService;
import com.bmadmin.util.BMUtil;
import com.bmadmin.util.Constants;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/zcck")
public class ZcckController {
private Logger logger = LogManager.getLogger(this.getClass().getName());
	
    @Autowired
    ZcckService zcckService;
    @Autowired
    ZcrkService zcrkService;
    @Autowired
    ZcwhService zcwhService;
    
    /**
     * 获取资产列表
     */
	@GetMapping("/getCkList")
    public Object getCkList(HttpSession session,ZcckDomain zcckDomain,Integer page,Integer limit) {
    	Datagrid result = new Datagrid();
    	SysUsersPOJO user=(SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
    	
    	Map map = new HashMap();
		map.put("qs_date", zcckDomain.getQs_date());
		map.put("jz_date", zcckDomain.getJz_date());
		map.put("yxbz", zcckDomain.getYxbz());
		logger.info(zcckDomain);//列表条件输出
		
		PageHelper.startPage(page, limit);
		List<ZcckDomain> list = zcckService.getCkList(map);
		
		PageInfo pagelist = new PageInfo(list);
		
		result.setCode(0);
        result.setMsg("success");
        result.setData(list);
        result.setCount(pagelist.getTotal());

        return result;
    }
	
    @PostMapping("/insertZcck")
    public NormalResult insertZcck(HttpSession session,ZcckDomain zcck) {
    	String log = "出库单新增>>>>>>>>>>>";
    	logger.info(log+"参数【"+zcck+"】");
    	SysUsersPOJO user=(SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
    	zcck.setZcck_userid(user.getU_id());
    	zcck.setZcck_addtime(BMUtil.getNowTimeForString());
        NormalResult result = new NormalResult();
        try {
        	if(!BMUtil.isNotNull(zcck.getZc_bm())){
        		result.setCode("9999");
                result.setMsg("资产名称为空！");
                logger.info(log+"资产名称为空！");
                return result;
        	}
        	if(!BMUtil.isNotNull(zcck.getZcck_lx())){
        		result.setCode("9999");
                result.setMsg("出库类型为空！");
                logger.info(log+"出库类型为空！");
                return result;
        	}
        	if(!BMUtil.isNotNull(zcck.getZcck_sl())){
        		result.setCode("9999");
                result.setMsg("出库数量为空！");
                logger.info(log+"出库数量为空！");
                return result;
        	}
        	int retResult = zcckService.insertZcck(zcck);
        	if(retResult>0){
        		int ret = zcrkService.DelZcSl(zcck.getZc_bm(),zcck.getZcck_sl());
        		if(ret>0){
        			logger.info(log+"出库库存修改成功！");
        		}else{
        			logger.info(log+"出库库存修改失败！");
        		}
        		result.setCode("0000");
                result.setMsg("保存成功！");
                logger.info(log+"保存成功！");
        	}else{
        		result.setCode("9999");
                result.setMsg("保存失败！");
                logger.info(log+"保存失败！");
        	}
        	return result;
        } catch (Exception e) {
            result.setCode("9999");
            result.setMsg("资产出库异常！");
            logger.error(e);
        }
        return result;
    }
    
    @PostMapping("/delZcck")
    public NormalResult delZcck(HttpSession session,String zcck_id) {
    	SysUsersPOJO user=(SysUsersPOJO) session.getAttribute(Constants.USER_INFO_SESSION);
    	String log = "出库单作废>>>>>>>>>>>";
        NormalResult result = new NormalResult();
        if (BMUtil.isNullOrEmpty(zcck_id)) {
            result.setCode("9999");
            result.setMsg("传入出库单ID为空!");
            return result;
        }
    	Map map = new HashMap();
		map.put("zcck_id", zcck_id);
        List<ZcckDomain> list = zcckService.getCkList(map);
        if(list.size()>0){
        	ZcckDomain zcck = (ZcckDomain)list.get(0);
        	if(!zcck.getZcck_userid().equals(user.getU_id())){
        		result.setCode("9999");
                result.setMsg("作废失败：该出库单非您录入！");
                logger.info(log+"作废失败：该出库单非您录入！");
                return result;
        	}
        	Map map1 = new HashMap();
    		map1.put("zc_bm", zcck.getZc_bm());
        	List<ZcwhDomain> zclist = zcwhService.getZcList(map1);
        	if(zclist==null||zclist.size()==0){
        		result.setCode("9999");
                result.setMsg("作废失败：资产登记表不存在资产编码【"+zcck.getZc_bm()+"】的资产！");
                logger.info(log+"作废失败：资产登记表不存在资产编码【"+zcck.getZc_bm()+"】的资产！");
                return result;
        	}
        	ZcwhDomain zcwh = zclist.get(0);
        	Double zc_sl = Double.parseDouble(zcwh.getZc_sl());
        	Double zcck_sl = Double.parseDouble(zcck.getZcck_sl());
//        	if(zcck_sl>zc_sl){
//        		result.setCode("9999");
//                result.setMsg("作废失败：资产出库单出库数量大于资产库存数量，无法作废！");
//                logger.info(log+"作废失败：资产出库单出库数量大于资产库存数量，无法作废！");
//                return result;
//        	}
        	int retResult = zcckService.updateZcckYxbz(zcck_id);
        	if(retResult>0){
        		int ret = zcrkService.AddZcSl(zcck.getZc_bm(),zcck.getZcck_sl());
        		if(ret>0){
        			logger.info(log+"出库单作废库存修改成功！");
        		}else{
        			logger.info(log+"出库单作废库存修改失败！");
        		}
        		result.setCode("0000");
                result.setMsg("作废成功！");
                logger.info(log+"作废成功！");
        	}else{
        		result.setCode("9999");
        		result.setMsg("作废失败：操作数据库失败！");
        		logger.info(log+"作废失败：操作数据库失败！");
        	}
        }else{
        	result.setCode("9999");
            result.setMsg("作废失败：未找到对应的出库单！");
            logger.info(log+"作废失败：未找到对应的出库单！");
        }
    	return result;
    }
    
    /**
     * 获取资产出库统计查询列表
     */
    @GetMapping("/getCktjcxList")
    public Object getCktjcxList(HttpSession session,ZcckDomain zcckDomain,Integer page,Integer limit) {
    	LayUiDataTablePOJO result = new LayUiDataTablePOJO();
    	
    	Map map = new HashMap();
		map.put("qs_date", zcckDomain.getQs_date());
		map.put("jz_date", zcckDomain.getJz_date());
		logger.info(zcckDomain);//列表条件输出

        List<ZccktjcxDomain> list = zcckService.getCktjcxList(map);
        result.setCode(0);
        result.setMsg("查询成功");
        result.setData(list);
        result.setCount(list.size());
        
        logger.info(result);
        return result;
    }
    
    /**
     *资产出库统计查询导出
     */
    @PostMapping("/exportCktjcx")
    public Object exportCktjcx(HttpSession session,ZcckDomain zcckDomain) {
		String log = "资产出库统计查询导出>>>>>>>>>>>";
		NormalResult result = new NormalResult();
		
		Map map = new HashMap();
		map.put("qs_date", zcckDomain.getQs_date());
		map.put("jz_date", zcckDomain.getJz_date());
		logger.info(zcckDomain);//列表条件输出

        List<ZccktjcxDomain> list = zcckService.getCktjcxList(map);
        if(list!=null&&list.size()>0){
        	// 声明一个工作薄
    		HSSFWorkbook workbook = new HSSFWorkbook();
    		// 用于格式化单元格的数据
    		HSSFDataFormat format = workbook.createDataFormat();

    		HSSFCellStyle stylecol = workbook.createCellStyle();
    		stylecol.setDataFormat(format.getFormat("@"));
    		// 设置单元格类型
    		HSSFCellStyle cellStyle = workbook.createCellStyle();
    		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平布局：居中
    		cellStyle.setWrapText(true);

    		HSSFSheet sheet = workbook.createSheet();
    		// 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    		HSSFRow row = sheet.createRow((int) 0);
    		sheet.autoSizeColumn(1, true);

    		HSSFFont font = workbook.createFont();
    		/*
    		 * font.setFontName("黑体"); font.setFontHeightInPoints((short)
    		 * 16);//设置字体大小 HSSFFont font2 = workbook.createFont();
    		 * font2.setFontName("仿宋_GB2312");
    		 * font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
    		 * font2.setFontHeightInPoints((short) 12);
    		 */
    		font.setColor(HSSFColor.RED.index);
    		
            // 创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

            HSSFCell cell = row.createCell(0);
            cell.setCellValue("序号");
    		cell.setCellStyle(style);
    		
    		cell = row.createCell(1);
    		cell.setCellValue("资产编码");
    		cell.setCellStyle(style);
    		
    		cell = row.createCell(2);
    		cell.setCellValue("资产名称");
    		cell.setCellStyle(style);

    		cell = row.createCell(3);
    		cell.setCellValue("资产分类");
    		cell.setCellStyle(style);

    		cell = row.createCell(4);
    		cell.setCellValue("出库数量");
    		cell.setCellStyle(style);
    		
    		
    		for (int i = 0; i < list.size(); i++) {
    			row = sheet.createRow((int) i + 1);
    			// ，创建单元格，并设置值
    			cell = row.createCell(0);
    			cell.setCellValue(i + 1);
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(0, stylecol);

    			cell = row.createCell(1);
    			cell.setCellValue(list.get(i).getZc_bm());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(1, stylecol);

    			cell = row.createCell(2);
    			cell.setCellValue(list.get(i).getZc_mc());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(2, stylecol);

    			cell = row.createCell(3);
    			cell.setCellValue(list.get(i).getZcfl_mc());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(3, stylecol);

    			cell = row.createCell(4);
    			cell.setCellValue(list.get(i).getZcck_sl());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(4, stylecol);
    		}
    		FileOutputStream fos = null;
            String uuid = BMUtil.getUUID();
    		try {
                String filename = "D:\\soft\\nginx\\html\\hzwgs\\exportfile\\"+uuid+".xls";

                fos = new FileOutputStream(filename);

                workbook.write(fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    		result.setCode("0000");
            result.setMsg("Excel文件获取成功！");
            result.setObject(uuid);
            logger.info(log+"Excel文件获取成功！");
        }else{
        	result.setCode("9999");
            result.setMsg("无导出数据");
            logger.info(log+"无导出数据！");
        }
        
		return result;
	}
	
    /**
     * 获取资产申请明细查询列表
     */
	@GetMapping("/getCkmxcxList")
    public Object getCkmxcxList(HttpSession session,ZcckDomain zcckDomain,Integer page,Integer limit) {
		LayUiDataTablePOJO result = new LayUiDataTablePOJO();

    	Map map = new HashMap();
		map.put("qs_date", zcckDomain.getQs_date());
		map.put("jz_date", zcckDomain.getJz_date());
		map.put("zcck_lx", zcckDomain.getZcck_lx());
		logger.info(zcckDomain);//列表条件输出
		
        List<ZcckmxcxDomain> list = zcckService.getCkmxcxList(map);
        result.setCode(0);
        result.setMsg("查询成功");
        result.setData(list);
        result.setCount(list.size());
        logger.info(result);
        return result;
    }
	
    /**
     *资产申请明细查询导出
     */
    @PostMapping("/exportCkmxcx")
    public Object exportCkmxcx(HttpSession session,ZcckDomain zcckDomain) {
		String log = "资产申请明细查询导出>>>>>>>>>>>";
		NormalResult result = new NormalResult();
		
		Map map = new HashMap();
		map.put("qs_date", zcckDomain.getQs_date());
		map.put("jz_date", zcckDomain.getJz_date());
		map.put("zcck_lx", zcckDomain.getZcck_lx());
		logger.info(zcckDomain);//列表条件输出

        List<ZcckmxcxDomain> list = zcckService.getCkmxcxList(map);
        if(list!=null&&list.size()>0){
        	// 声明一个工作薄
    		HSSFWorkbook workbook = new HSSFWorkbook();
    		// 用于格式化单元格的数据
    		HSSFDataFormat format = workbook.createDataFormat();

    		HSSFCellStyle stylecol = workbook.createCellStyle();
    		stylecol.setDataFormat(format.getFormat("@"));
    		// 设置单元格类型
    		HSSFCellStyle cellStyle = workbook.createCellStyle();
    		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平布局：居中
    		cellStyle.setWrapText(true);

    		HSSFSheet sheet = workbook.createSheet();
    		// 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    		HSSFRow row = sheet.createRow((int) 0);
    		sheet.autoSizeColumn(1, true);

    		HSSFFont font = workbook.createFont();
    		/*
    		 * font.setFontName("黑体"); font.setFontHeightInPoints((short)
    		 * 16);//设置字体大小 HSSFFont font2 = workbook.createFont();
    		 * font2.setFontName("仿宋_GB2312");
    		 * font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
    		 * font2.setFontHeightInPoints((short) 12);
    		 */
    		font.setColor(HSSFColor.RED.index);
    		
            // 创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

            HSSFCell cell = row.createCell(0);
            cell.setCellValue("序号");
    		cell.setCellStyle(style);
    		
    		cell = row.createCell(1);
    		cell.setCellValue("资产编码");
    		cell.setCellStyle(style);
    		
    		cell = row.createCell(2);
    		cell.setCellValue("资产名称");
    		cell.setCellStyle(style);

    		cell = row.createCell(3);
    		cell.setCellValue("资产分类");
    		cell.setCellStyle(style);

    		cell = row.createCell(4);
    		cell.setCellValue("出库数量");
    		cell.setCellStyle(style);

    		cell = row.createCell(5);
    		cell.setCellValue("出库时间");
    		cell.setCellStyle(style);

    		cell = row.createCell(6);
    		cell.setCellValue("申请人");
    		cell.setCellStyle(style);
    		
    		cell = row.createCell(7);
    		cell.setCellValue("处理人");
    		cell.setCellStyle(style);
    		
    		cell = row.createCell(8);
    		cell.setCellValue("出库类型");
    		cell.setCellStyle(style);
    		
    		for (int i = 0; i < list.size(); i++) {
    			row = sheet.createRow((int) i + 1);
    			// ，创建单元格，并设置值
    			cell = row.createCell(0);
    			cell.setCellValue(i + 1);
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(0, stylecol);

    			cell = row.createCell(1);
    			cell.setCellValue(list.get(i).getZc_bm());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(1, stylecol);

    			cell = row.createCell(2);
    			cell.setCellValue(list.get(i).getZc_mc());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(2, stylecol);

    			cell = row.createCell(3);
    			cell.setCellValue(list.get(i).getZcfl_mc());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(3, stylecol);

    			cell = row.createCell(4);
    			cell.setCellValue(list.get(i).getZcck_sl());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(4, stylecol);

    			cell = row.createCell(5);
    			cell.setCellValue(list.get(i).getZ_back_date());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(5, stylecol);

    			cell = row.createCell(6);
    			cell.setCellValue(list.get(i).getZ_apply_usename());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(6, stylecol);
    			
    			cell = row.createCell(7);
    			cell.setCellValue(list.get(i).getZ_receive_usename());
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(7, stylecol);
    			
    			cell = row.createCell(8);
    			String cklx_mc = "";
    			if("0".equals(list.get(i).getZcck_lx())){
    				cklx_mc = "正常出库";
    			}else if("1".equals(list.get(i).getZcck_lx())){
    				cklx_mc = "补偿出库";
    			}else{
    				cklx_mc = "申请出库";
    			}
    			cell.setCellValue(cklx_mc);
    			cell.setCellStyle(style);
    			sheet.setDefaultColumnStyle(8, stylecol);
    		}
    		FileOutputStream fos = null;
            String uuid = BMUtil.getUUID();
    		try {
                String filename = "D:\\soft\\nginx\\html\\hzwgs\\exportfile\\"+uuid+".xls";

                fos = new FileOutputStream(filename);

                workbook.write(fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    		result.setCode("0000");
            result.setMsg("Excel文件获取成功！");
            result.setObject(uuid);
            logger.info(log+"Excel文件获取成功！");
        }else{
        	result.setCode("9999");
            result.setMsg("无导出数据");
            logger.info(log+"无导出数据！");
        }
        
		return result;
	}
}
